<template>
  <div class="ticket-choose-container">
    <h2 class="section-header">旅程信息选择</h2>

    <el-card class="ticket-card">
      <el-table
        ref="ticketTable"
        :data="ticketList"
        tooltip-effect="dark"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="70" label="勾选框"></el-table-column>
        <el-table-column prop="type" label="类型"></el-table-column>
        <el-table-column prop="departure" label="出发地点"></el-table-column>
        <el-table-column prop="arrival" label="到达地点"></el-table-column>
        <el-table-column prop="way" label="交通工具"></el-table-column>
        <el-table-column prop="startTime" label="出发时间"></el-table-column>
        <el-table-column prop="endTime" label="结束时间"></el-table-column>
        <el-table-column prop="price" label="金额"></el-table-column>
      </el-table>
    </el-card>

    <!-- 注意事项 -->
    <el-card class="notice-card">
      <div class="notice">
        <h3>注意事项</h3>
        <p>1. 按照时间顺序排序</p>
        <p>2. 选择的车票的出发地必须闭环</p>
        <p>
          3. 将车票的最早出发时间、最晚到达时间获取，传回差旅新增页面；
          所有车票金额累计，传回差旅新增页面。
        </p>
      </div>
    </el-card>

    <!-- 底部按钮 -->
    <div class="bottom-actions">
      <el-button type="primary" @click="confirmSelect">确定</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "TicketChoose",
  props: {
    travelId: Number,
    empno: Number,
    selectedTicketsFromParent: Array,
  },
  data() {
    return {
      ticketList: [],
      selectedTickets: [],
    };
  },
  mounted() {
    this.getTickets();
  },
  methods: {
    async getTickets() {
      const empno = localStorage.getItem('empno');
      const travelId = this.travelId;
      this.$http.get('/getTicketByEmpno?empno=' + empno + '&travelId=' + travelId).then(res => {
        if(res.status === 200) {
          this.ticketList = res.data || []

          this.$nextTick(() => {
            this.restoreSelection()
          })
        }
      })
    },

    // 自动恢复已选择的车票
    restoreSelection() {
      if (!this.selectedTicketsFromParent) {
        return;
      }
      this.ticketList.forEach(ticket => {
        const matched = this.selectedTicketsFromParent.find(i => i.ticketId === ticket.ticketId);
        if (matched) {
          this.$refs.ticketTable.toggleRowSelection(ticket, true);
        }
      });
    },

    handleSelectionChange(val) {
      this.selectedTickets = val;
    },

    confirmSelect() {
      if (this.selectedTickets.length === 0) {
        this.$message.warning("请至少选择一条车票");
        return;
      }
      //按出发时间排序
      const sortedTickets = [...this.selectedTickets].sort(
        (a, b) => new Date(a.startTime) - new Date(b.startTime)
      );

      //校验时间是否重叠
      for (let i = 0; i < sortedTickets.length - 1; i++) {
        const currentEnd = new Date(sortedTickets[i].endTime);
        const nextStart = new Date(sortedTickets[i + 1].startTime);
        if (currentEnd > nextStart) {
          this.$message.error("所选车票时间存在重叠，请重新选择");
          return;
        }
      }

      // 校验行程闭环
      for (let i = 0; i < sortedTickets.length - 1; i++) {
        if (sortedTickets[i].arrival !== sortedTickets[i + 1].departure) {
          this.$message.error("所选车票未形成闭环（中间站点不连贯），请重新选择");
          return;
        }
      }

      if (sortedTickets[0].departure !== sortedTickets[sortedTickets.length - 1].arrival) {
        this.$message.error("所选车票未形成闭环（起点与终点不一致），请重新选择");
        return;
      }

      
      let count = 0;
      for(let i = 0; i < sortedTickets.length; i++) {
        if(sortedTickets[i].type === "返回") {
          count++;
        }
      }
      if(count > 1 || count == 0) {
        this.$message.error("所选车票应有也只能有一个环路");
        return;
      }

      this.$emit("confirm", sortedTickets);
    }
  }
};
</script>

<style scoped>
.ticket-choose-container {
  padding: 20px;
  background-color: #fff;
}
.section-header {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 10px;
}
.ticket-card {
  margin-bottom: 20px;
}
.notice-card {
  margin-bottom: 20px;
}
.notice {
  font-size: 14px;
  color: #333;
  line-height: 1.8;
}
.bottom-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  margin-top: 10px;
}
</style>
